package com.nodecollege.cloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.exception.UpmsException;
import com.nodecollege.cloud.common.model.BindVO;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.QueryRelationVO;
import com.nodecollege.cloud.common.model.QueryVO;
import com.nodecollege.cloud.common.model.po.UpmsMenu;
import com.nodecollege.cloud.common.model.po.UpmsRole;
import com.nodecollege.cloud.common.model.po.UpmsRoleMenu;
import com.nodecollege.cloud.common.utils.NCUtils;
import com.nodecollege.cloud.dao.mapper.UpmsMenuMapper;
import com.nodecollege.cloud.dao.mapper.UpmsRoleMapper;
import com.nodecollege.cloud.dao.mapper.UpmsRoleMenuMapper;
import com.nodecollege.cloud.service.MenuService;
import com.nodecollege.cloud.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LC
 * @date 2020/1/8 19:10
 */
@Service
public class RoleMenuServiceImpl implements RoleMenuService {

    @Autowired
    private UpmsRoleMenuMapper upmsRoleMenuMapper;

    @Autowired
    private UpmsRoleMapper upmsRoleMapper;

    @Autowired
    private UpmsMenuMapper upmsMenuMapper;

    @Autowired
    private MenuService menuService;

    /**
     * 根据菜单查询角色列表
     *
     * @param query
     * @return
     */
    @Override
    public NCResult<UpmsRole> getRoleListByMenuId(QueryRelationVO<UpmsRole, UpmsMenu> query) {
        NCUtils.nullOrEmptyThrow(query.getEndNode().getMenuId(), new UpmsException("", "菜单id不能为空！"));
        List<UpmsRole> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(query.getPageSize())) {
            list = upmsRoleMapper.selectRoleListJoinRoleMenu(query.toMap());
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
            if (query.isSort()) {
                page.setOrderBy(query.getSortKey() + " " + query.getSortDirection());
            }
            list = upmsRoleMapper.selectRoleListJoinRoleMenu(query.toMap());
            total = page.getTotal();
        }
        return NCResult.ok(list, total);
    }

    /**
     * 系统管理 角色管理 查询租户有权限的 已经绑定的菜单信息 入参 tenantId roleId
     * 运维管理 应用预制角色管理 查询角色已绑定菜单信息 入参 appId roleId
     *
     * @param query
     * @return
     */
    @Override
    public List<UpmsMenu> getMenuListByRoleId(UpmsRole query) {
        NCUtils.nullOrEmptyThrow(query.getRoleId(), new UpmsException("", "角色id不能为空！"));
        NCUtils.nullOrEmptyThrow(query.getRoleSource(), new UpmsException("", "角色来源不能为空！"));
        if (NCConstants.INT_1.equals(query.getRoleSource())) {
            // 系统管理 角色管理 查询租户有权限的 已经绑定的菜单信息 入参 tenantId roleId
            NCUtils.nullOrEmptyThrow(query.getTenantId(), new UpmsException("", "租户id不能为空"));
            query.setRoleSource(null);
            return upmsMenuMapper.selectListByTenantIdAndRoleId(new QueryVO<>(query).toMap());
        }
        if (NCConstants.INT_0.equals(query.getRoleSource())) {
            // 运维管理 应用预制角色管理 查询角色已绑定菜单信息 入参 appId roleId
            NCUtils.nullOrEmptyThrow(query.getAppId(), new UpmsException("", "应用id不能为空"));
            return upmsMenuMapper.selectListByRoleId(new QueryVO<>(query).toMap());
        }
        throw new UpmsException("", "参数错误");
    }

    /**
     * 绑定/解绑角色菜单关系
     *
     * @param bindVO
     */
    @Override
    public void bindRoleMenu(BindVO bindVO) {
        NCUtils.nullOrEmptyThrow(bindVO.getMainSource(), new UpmsException("-1", "参数错误！"));

        // 已绑定的数据
        UpmsRoleMenu query = new UpmsRoleMenu();
        query.setTenantId(bindVO.getTenantId());
        query.setAppId(bindVO.getAppId());
        if (bindVO.getMainSource()) {
            NCUtils.nullOrEmptyThrow(bindVO.getSourceIds(), new UpmsException("", "绑定入参有误！"));
            query.setRoleId(bindVO.getSourceIds().get(0));
        } else {
            NCUtils.nullOrEmptyThrow(bindVO.getTargetIds(), new UpmsException("", "绑定入参有误！"));
            query.setMenuId(bindVO.getTargetIds().get(0));
        }
        List<UpmsRoleMenu> exList = upmsRoleMenuMapper.selectListByRoleMenu(query);

        // 最终保留的数据
        List<UpmsRoleMenu> endList = new ArrayList<>(bindVO.getSourceIds().size() * bindVO.getTargetIds().size());
        bindVO.getSourceIds().forEach(orgId -> {
            bindVO.getTargetIds().forEach(memberId -> {
                UpmsRoleMenu end = new UpmsRoleMenu();
                end.setMenuId(memberId);
                end.setRoleId(orgId);
                end.setTenantId(bindVO.getTenantId());
                end.setAppId(bindVO.getAppId());
                endList.add(end);
            });
        });

        // 取消绑定的数据
        exList.forEach(ex -> {
            Boolean delFlag = true;
            for (int i = 0; i < endList.size(); i++) {
                if (ex.getRoleId().equals(endList.get(i).getRoleId())
                        && ex.getMenuId().equals(endList.get(i).getMenuId())) {
                    delFlag = false;
                    break;
                }
            }
            if (delFlag) {
                upmsRoleMenuMapper.deleteByPrimaryKey(ex.getRoleMenuId());
            }
        });

        // 新增绑定的数据
        endList.forEach(end -> {
            Boolean addFlag = true;
            for (int i = 0; i < exList.size(); i++) {
                if (end.getRoleId().equals(exList.get(i).getRoleId())
                        && end.getMenuId().equals(exList.get(i).getMenuId())) {
                    addFlag = false;
                    break;
                }
            }
            if (addFlag) {
                upmsRoleMenuMapper.insert(end);
            }
        });
    }
}
